package com.lagou.config;

import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author Kirito
 * @description: 基于单一设计原则，解析xml文件交给XmlConfigBuilder来做
 * @date 2020/03/25
 */
public class XmlConfigBuilder {

    private Configuration configuration;

    /**
     * constructor
     */
    public XmlConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 使用dom4j解析xml文件并封装成Configuration对象
     *
     * @param inputStream InputStream
     * @return Configuration
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        // 1.解析sqlMapConfig.xml核心配置文件
        Document document = new SAXReader().read(inputStream);
        // rootElement = <configuration>
        Element rootElement = document.getRootElement();
        List<Element> propertyElements = rootElement.selectNodes("//property");
        // 通过Properties对象来存储<property>标签中的属性k-v值，方便后面获取
        Properties properties = new Properties();
        for (Element propertyElement : propertyElements) {
            // propertyElement = <property>
            String name = propertyElement.attributeValue("name");
            String value = propertyElement.attributeValue("value");
            properties.setProperty(name, value);
        }

        // 创建连接池
        ComboPooledDataSource pooledDataSource = new ComboPooledDataSource();
        pooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        pooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        pooledDataSource.setUser(properties.getProperty("username"));
        pooledDataSource.setPassword(properties.getProperty("password"));

        configuration.setDataSource(pooledDataSource);

        // 2.解析mapper.xml文件
        XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(configuration);
        List<Element> mapperElements = rootElement.selectNodes("//mapper");
        for (Element mapperElement : mapperElements) {
            // mapperElement = <mapper>
            String mapperPath = mapperElement.attributeValue("resource");
            InputStream mapperStream = Resources.getResourcesAsStream(mapperPath);
            xmlMapperBuilder.parseMapper(mapperStream);
        }

        return configuration;
    }
}
